import 'dart:convert';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_wanandroid/common/api.dart';
import 'package:flutter_wanandroid/entity/hot_entity.dart';
import 'package:flutter_wanandroid/entity/hot_entity2.dart';
import 'package:flutter_wanandroid/httpUtils/http_util.dart';
import 'package:flutter_wanandroid/pages/flutter_webview.dart';
import 'package:flutter_wanandroid/res/colors.dart';

import '../entity/article_entity.dart';

List<Datum> _data = [];
String key = "";
List<DatasBean> articleDatas = [];

List<DatasBean> _articleData = [];

class ArticleDataData {}

class SearchPage extends StatefulWidget {
  const SearchPage({Key? key}) : super(key: key);

  @override
  State<SearchPage> createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> {
  @override
  void initState() {
    super.initState();
    getHttpByHoyKey();
  }

  void getHttpByHoyKey() async {
    var response = await HttpUtil().get(Api.HOT_KEY);
    // Map<String, dynamic> map = json.decode(response.toString());
    // HotEntity? fromMap = HotEntity.fromMap(map);
    HotEntity2 data = welcomeFromJson(response);
    if (mounted) {
      setState(() {
        _data = data.data ?? [];
      });
      showSearch(context: context, delegate: MySearchDelegate("输入你想搜的内容~"));
    }
  }

  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      backgroundColor: Colors.white,
      body: null,
    );
  }
}

class MySearchDelegate extends SearchDelegate<String> {
  BuildContext get context => context;

  MySearchDelegate(String hintText)
      : super(
          searchFieldLabel: hintText,
          keyboardType: TextInputType.text,
          //// 软键盘快捷键
          textInputAction: TextInputAction.search,
          //输入的字体颜色
          searchFieldStyle: const TextStyle(color: Colors.white),
        );

  // List<DatasBean>? articleDatas;

  @override
  List<Widget>? buildActions(BuildContext context) {
    return [
      TextButton(
        onPressed: () async {
          var data = {'k': query};
          var articleResponse = await HttpUtil().post(Api.QUERY, data: data);
          Map<String, dynamic> articleMap =
              json.decode(articleResponse.toString());
          ArticleEntity? articleEntity = ArticleEntity.fromMap(articleMap);
          articleDatas = articleEntity?.data?.datas ?? [];

          showResults(context);
        },
        child: const Text(
          "搜索",
          style: TextStyle(
            color: Colors.white,
          ),
        ),
      ),
      // 显示一个清除的按钮
      IconButton(
        icon: Icon(Icons.clear),
        onPressed: () {
          query = "";
          showSuggestions(context);
        },
      ),
    ];
  }

  @override
  Widget? buildLeading(BuildContext context) {
    return IconButton(
      onPressed: () {
        close(context, "");
        Navigator.pop(context);
      },
      icon: AnimatedIcon(
          icon: AnimatedIcons.menu_arrow, progress: transitionAnimation),
    );
  }

  @override
  Widget buildResults(BuildContext context) {
    return ListView.builder(
      itemCount: articleDatas.length,
      itemBuilder: (context, index) {
        return GestureDetector(
          child: Padding(
            padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 20),
            child: ListTile(
              title: Text(
                  articleDatas[index].title!.replaceAll("<em class='highlight'>", "【").replaceAll("<\/em>", "】"),
                  style: const TextStyle(
                      color: YColors.color_666, fontWeight: FontWeight.bold),
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis),
              trailing: const Icon(Icons.chevron_right),
              subtitle: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Container(
                    padding: EdgeInsets.symmetric(horizontal: 10),
                    constraints: const BoxConstraints(maxWidth: 150),
                    decoration: BoxDecoration(
                        border: Border.all(
                            color: Theme.of(context).primaryColor, width: 1),
                        borderRadius: BorderRadius.circular(20)),
                    child: Text(
                      articleDatas[index].superChapterName ?? "",
                      style: TextStyle(color: Theme.of(context).primaryColor),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),

                  const SizedBox(width: 50,),
                  Text(articleDatas[index].author ?? "", style: TextStyle(
                    fontSize: 14
                  ),)
                ],
              ),
            ),
          ),
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => FlutterWebView(
                    title: articleDatas[index].title!.replaceAll("<em class='highlight'>", "【").replaceAll("<\/em>", "】"),
                    uri: articleDatas[index].link),
              ),
            );
          },
        );
      },
    );
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(15),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text("大家都在搜"),
          Wrap(
            spacing: 10,
            children: List<Widget>.generate(
              _data.length,
              (index) => ActionChip(
                label: Text(
                  _data[index].name ?? "",
                  style: TextStyle(color: Colors.white),
                ),
                onPressed: () async {
                  query = _data[index].name ?? "";
                  key = query;

                  /// 请求数据
                  var data = {'k': key};
                  var articleResponse =
                      await HttpUtil().post(Api.QUERY, data: data);
                  Map<String, dynamic> articleMap =
                      json.decode(articleResponse.toString());
                  var articleEntity = ArticleEntity.fromMap(articleMap);

                  articleDatas = articleEntity?.data?.datas ?? [];

                  /// 显示结果
                  showResults(context);
                },
                elevation: 5,
                backgroundColor: Color.fromARGB(
                  180,
                  Random().nextInt(255),
                  Random().nextInt(255),
                  Random().nextInt(255),
                ),
              ),
            ).toList(),
          )
        ],
      ),
    );
  }

  @override
  ThemeData appBarTheme(BuildContext context) {
    return Theme.of(context).copyWith(
      //主题色
      primaryColor: Theme.of(context).primaryColor,
      //图标颜色
      primaryIconTheme:
          Theme.of(context).primaryIconTheme.copyWith(color: Colors.white),
      //状态栏
      primaryColorBrightness: Brightness.dark,
      //文字主题
      textTheme: Theme.of(context).textTheme.copyWith(
            headline1: Theme.of(context).textTheme.headline1?.copyWith(
                color: Theme.of(context).primaryTextTheme.headline1?.color ??
                    Colors.white),
            subtitle1: const TextStyle(
              color: Colors.red,
              fontWeight: FontWeight.bold,
              fontSize: 18,
            ),
          ),
    );
  }
}
